<template>
    <div>
        <div style="margin-top: 15px;">
            <Button type="primary" class="md-add-jh" @click='addColTaskBtn'>添加采集任务</Button>
        </div>
        <Table :columns="colTask" :data="colTaskList" style="margin-top: 15px;"></Table>
        <div style="display: flex;justify-content: center;margin: 15px 0">
            <Page :total=colTotal :page-size="colPageSize" :current="colPage" show-total show-elevator @on-change="colChangePage"/>
        </div>
        <!-- 添加采集任务 -->
        <Modal
            v-model="addColModel" width="600"
            :mask-closable="false"
            :footer-hide="true"
            title="添加采集任务">
            <Form ref="colFormV" :model="colFormV" :rules="colFormVRule" :label-width="80">
                <FormItem label="名字" prop="name">
                    <Input v-model="colFormV.name" placeholder="采集任务名称" clearable :maxlength="64"></Input>
                </FormItem>
                <FormItem label="配置" prop="configId" style="position:relative">
                    <Select filterable v-model="colFormV.configId" placeholder="请选择配置" label-in-value filterable clearable @on-change="showConfiguration">
                        <Option  v-for="item in configurationData" :key="item.id" :value="item.id"  
                        @mouseenter.native="mouseOverConfiger($event,item.id)" @mouseleave.native="mouseLeaveConfiger($event,item.id)" 
                        @click.native="ddd">{{item.name}}</Option>
                    </Select>
                    <div v-show="configurationInformation" :style="{position:'absolute',left:cardPanelLeft,top:cardPanelTop,zIndex:'99999999',}" >
                        <Card :style="{minWidth:'350px',maxWidth:'600px'}"  >
                            <p slot="title" style="position:relative">
                                <Icon type="ios-construct"></Icon>
                                {{configPanel.configName}}
                                <span slot="title" style="position:absolute;right:0px">
                                    <Icon type="ios-contact"></Icon>
                                    {{configPanel.configCreatorName}}
                                </span>
                            </p>
                            <ul>
                                <li><span class="_dot"></span>Systype：{{configPanel.configSystype}}</li>
                                <li><span class="_dot"></span>Cmd：{{configPanel.configPath}}</li>
                                <li><span class="_dot"></span>Parameters：{{configPanel.configContent}}</li>
                                <li><span class="_dot"></span>CreateTime：{{configPanel.configCreateTime}}</li>
                                <li><span class="_dot"></span>Desc：{{configPanel.configDescription}}</li>
                            </ul>
                        </Card>
                    </div>
                </FormItem>
                <FormItem v-model="colFormV.selectedVmData"  label="虚拟机" >
                    <span class="starlet">*</span>
                    <input type="hidden" >
                    <Tag v-for="item in colFormV.selectedVmData" :key="item.name" :name="item.id" closable @on-close="handleClose2" 
                    color="primary" type='dot' >{{ item.name }}</Tag>
                </FormItem>
                <div style="text-align:right">
                    <Button type="primary" @click="addSelectedData" style="margin-right:17px">添加</Button>
                    <Select filterable placeholder="子网" style="width: 149px" label-in-value filterable clearable @on-change="filterNetVm">
                        <Option  v-for="item in subnetList" :key="item.id" :value="item.id" :title="item.name">{{item.name}}</Option>
                    </Select>
                    <Input placeholder="搜索名称" style="width: 150px" v-model='vmName' clearable></Input>
                    <Input placeholder="搜索IP" style="width: 120px" v-model='vmIP' clearable></Input>
                    <Button type="primary" @click="refreshVmList" style="margin-left:5px">搜索</Button>
                </div>
                <Table border ref="" :columns="columnsVmList" :data="dataVmList"  :stripe="showStripe" :show-header="showHeader" :size="tableSize" style="margin-top:5px"  @on-selection-change="getSelectedData"></Table>
                <Page :total="vmTotal" show-elevator :current="vmCurrentPage" :page-size="vmItemPage" :show-total= true  @on-change="switchineVmCurrentPage" @on-page-size-change="switchVmItemPage" class-name="pageStyleVm"/>
                <FormItem>
                    <Button type="primary" @click="colSubmitBtn('colFormV')" :loading='colLoading'>确定</Button>
                    <Button @click="resetBtn('colFormV')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
    import $ from 'jquery'
    import {checkTaskList,colTaskList,jbConfList,configInfo,getVmList,addCollTask,delColTask,modifyColTask,subnetData } from '@/api/train.js'
    export default {
        data () {
            return {
                setBtnState:'',
                sceneID:this.$route.query.id,
                projectId:this.$route.query.projectId,
                // 采集任务
                colTaskList:[],
                colTask:[
                    {
                        type: 'index',
                        width: 60,
                    },
                    {
                        title:'采集任务名称',
                        key:'name',
                        align:'center'
                    },
                    {
                        title:'配置名称',
                        key:'configName',
                        align:'center'
                    },
                    {
                        title:'任务类型',
                        key:'taskType',
                        align:'center'
                    },
                    {
                        title:'创建者',
                        key:'creatorName',
                        align:'center'
                    },
                    {
                        title:'创建时间',
                        key:'createTime',
                        align:'center'
                    },
                    {
                        title:'操作',
                        key:'action',
                        align:'center',
                        render:(h,params)=>{
                            let flag = true
                            return h('a',{
                                attrs: {
                                    disabled:flag?false:true,
                                },
                                style: {
                                    'display': 'flex',
                                    'justify-content': 'center',
                                },
                            },[
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            transfer:true,
                                            title: '确定要删除吗？'
                                        },
                                        on: {
                                            'on-ok': ()=>{
                                                this.delColTask(params.row)
                                            },
                                            'on-cancel': ()=>{

                                            }
                                        }
                                    },
                                    [
                                        h('img', {
                                            attrs: {
                                                src: flag?require('../../../assets/project/delNote-h.png'):require('../../../assets/project/delNote-d.png'),
                                            },
                                            style: {
                                                cursor: 'pointer',
                                                'margin-right':'5px',
                                                'vertical-align': 'middle',
                                                width:'16px',
                                                height:'16px',
                                                display:'inline-block',
                                            },
                                        }),
                                    ],
                                ),
                                h('div', {
                                    on: {
                                        'click': ()=>{
                                            this.modifyTask(params.row)
                                        },
                                    },
                                    style:{
                                        'margin-left':'15px',
                                    }
                                }, [
                                    h('img', {
                                        attrs: {
                                            src: flag?require('../../../assets/project/modifys-h.png'):require('../../../assets/project/modifys.png'),
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            'margin-right':'5px',
                                            'vertical-align': 'middle',
                                            width:'16px',
                                            height:'16px',
                                            display:'inline-block',
                                        },
                                    }),
                                ])
                            ])
                        }
                    },
                ],
                colTotal:0,
                colPageSize:10,
                colPage:1,
                // 添加采集任务
                addColModel:false,
                colFormV:{
                    configId:'',
                    configName:'',
                    taskType:'qga_execute_cmd',
                    name:'',
                    trainingId:'',
                    selectedVmData:[],
                },
                colFormVRule:{
                    name: [
                        { required: true,max: 64, message: '名称长度为1—64个字符', trigger: 'change' },
                    ],
                    configId: [
                        { required: true, message: '请选择配置', trigger: 'change' }
                    ],
                    // selectedVmData: [
                    //     { required: true, message: '请选择虚拟机', trigger: 'change' }
                    // ],
                },
                configurationData:[],  // 采集配置列表
                optionHoverEvent:null,
                optionOutEvent:null,
                configurationInformation:false,
                cardPanelLeft:'3px',
                cardPanelTop:'3px',
                configPanel:{
                    configPath:'',
                    configSystype:'',
                    configContent:'',
                    configDescription:'',
                    configCreateTime:'',
                    configCreatorName:'',
                    configName:'',
                },
                selectedDataConfiger:[],
                selectedVmDataTable:[],
                dataVmList:[],
                modifyId:'',
                // 虚拟机列表
                dataVmList:[],
                showStripe: true,
                showHeader: true,
                showIndex: true,
                colLoading:false,
                tableSize: 'small',
                vmTotal:0,
                vmCurrentPage:1,
                vmItemPage:10,
                showCheckbox: false,
                columnsVmList:[
                    {
                        type:'selection',
                        width:60,
                        align:'center'
                    },
                    {
                        title:'名称',
                        key:'name',
                        align:'center'
                    },
                    {
                        title:'IP',
                        key:'IP',
                        align:'center',
                        render:(h,params)=>{
                            let value = params.row.IP;
                            let oIP_ = [];
                            $.each(value,(i,item)=>{
                                oIP_.push(h("p",{
                                    color:'#000',
                                },item))
                            })
                            return h("div",oIP_)
                        }
                    },
                    {
                        title:'网络名称',
                        key:'networkName',
                        align:'center'
                    },
                    {
                        title:'添加',
                        key:'add',
                        align:'center',
                        render:(h,params) =>{
                            let _this = params;
                            return h('Button', {
                                props: {
                                    type: 'primary',
                                },
                                on:{
                                    click: (e) => {
                                        if(this.selectedVmDataTable.indexOf(_this.row.id)!=-1){
                                            this.$Message.info("已添加")
                                            return;
                                        }
                                        this.addVmAfterTable(_this.row)
                                        this.selectedVmDataTable.push(_this.row.id)
                                        this.colFormV.selectedVmData.push({
                                            "name":_this.row.name,
                                            "id":_this.row.id
                                        })
                                    },
                                }
                            }, "+");
                        }
                    }
                ],
                vmName:'',
                vmIP:'',
                isCreat:false,
                // 查询子网络列表
                subnetList:[],
                networkId:"",
            }
        },
        created(){
            
        },
        mounted(){
            this.getColData()
            this.getSubnetList()
        },
        watch: {
            // hidebtn(newVal) {
            //     this.setBtnState = newVal //对父组件传过来的值进行监听，如果改变也对子组件内部的值进行改变
            // },
        },
        methods:{
            // 采集任务
            getColData(){
                let params = {
                    pageIndex:this.colPage,
                    pageSize:this.colPageSize,
                    trainingId:this.sceneID,
                }
                colTaskList(params)
                .then(res=>{
                    if(res.data.code === 1){
                        this.colTaskList = res.data.data.records
                        this.colTotal = res.data.data.total
                    }else{
                        this.taskList = []
                        this.taskTotal = 0
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            colChangePage(val){
                this.colPage = val
                this.getColData()
            },
            // 弹窗model
            addColTaskBtn(){
                this.addColModel = true
                this.isCreat = true
                this.$refs['colFormV'].resetFields()
                this.selectedDataConfiger = []
                this.selectedVmDataTable = []
                this.colFormV.selectedVmData = []
                this.loadConfiguration("qga_execute_cmd")
                this.getVmList()
            },
            showConfiguration(value){
                this.colFormV.configName = value.label
                this.colFormV.configId = value.value
            },
            loadConfiguration(operation){
                let $this= this;
                let params = {
                    "operation":operation,
                    page:1,
                    size:10000,
                }
                jbConfList(params)
                .then((response)=>{
                    $this.configurationData = [];
                    if(response.data.code==1||response.data.code==0){
                        let ConfigurationList = response.data.data.list;
                        if(ConfigurationList==""){
                            return;
                        }
                        $.each(ConfigurationList, function(i,item) {
                            $this.configurationData.push({
                                name:item.name,
                                id:String(item.id),
                            })
                        });
                    }else{
                        $this.$Message.error(response.data.message)
                    }
                })
            },
            /**
             * @description: 鼠标移上配置显示详情
             * @param {type} 
             * @return: 
             */
            mouseOverConfiger(e,value){
                clearTimeout(this.optionHoverEvent)
                let _this = this;
                this.optionHoverEvent = setTimeout(() => {
                    if(this.hoverCdraBol){
                        return;
                    }
                    let scrollTop = navigator.userAgent.indexOf("Firefox") > 0 ? e.target.offsetParent.scrollTop : 0;
                    this.configurationInformation = true
                    this.cardPanelLeft = e.layerX +30+ 'px'
                    this.cardPanelTop = e.layerY - scrollTop +35+'px'
                    //查询配置详细信息
                    configInfo(value)
                    .then(function (response) {
                        if(response.data.code != '1'){
                            _this.$Message.warning(response.data.message);
                        }else{
                            let getData = response.data.data
                            _this.configPanel.configName = getData.name
                            _this.configPanel.configPath = getData.data.cmd
                            _this.configPanel.configSystype = getData.data.osType
                            _this.configPanel.configContent = getData.data.arg.map((item)=>{
                                return item
                            }).join(',')
                            _this.configPanel.configDescription = getData.description
                            _this.configPanel.configCreateTime = getData.createTime
                            _this.configPanel.configCreatorName = getData.creatorName
                        }
                    });
                }, 300);
            },
            mouseLeaveConfiger(ev,value){
                clearTimeout(this.optionOutEvent)
                this.optionOutEvent = setTimeout(() => {
                    if(!this.hoverCdraBol){
                        this.configurationInformation = false
                        this.cardPanelLeft = '0'
                        this.cardPanelTop = '0'
                    }
                }, 300);
            },
            ddd(e){
                e.preventDefault()
                e.stopPropagation();
            },
            handleClose2 (event, name) {
                let $this = this;
                let data = this.colFormV.selectedVmData;
                $this.selectedDataConfiger= [];
                let _data = this.selectedVmDataTable;
                $.each(data,function(i,item){
                    if(item){
                        if(item.id==name){
                            data.splice(i,1);
                            _data.splice(_data.findIndex(item => item === name), 1)
                            $this.judgeVmStatus(name)
                        }
                    }
                });
            },
            judgeVmStatus(name){
                let data = this.dataVmList;
                let data_ = this.selectedVmDataTable
                $.each(data,function(i,item){
                    if(item.id==name){
                        item._checked = false;
                        item._disabled = false;
                    }
                })
            },
            getSelectedData(selection){
                this.selectedDataConfiger = [];
                this.selectedDataConfiger = selection;
            },
            getVmList(){
                let $this = this;
                let data = {
                    pageIndex: 1,
                    pageSize: 10,
                    order: 'asc',
                    sortBy: 'name',
                }
                if(this.networkId != ''){
                    data.networkId = this.networkId
                }
                if(this.vmName){
                    data.name = this.vmName
                }
                if(this.vmIP){
                    data.ipAddress = this.vmIP
                }
                $this.dataVmList = [];
                getVmList({data:data,id:this.projectId})
                .then((response)=>{
                    if(response.data.code==1){
                        let vmData = response.data.data.items;
                        $this.vmTotal = Number(response.data.data.total);
                        let disabled_ = false;
                        let checked_ = false;
                        $.each(vmData,function(i,item){
                            if($this.selectedVmDataTable.length!=0){
                                if($this.selectedVmDataTable.indexOf(item.id)!=-1){
                                    disabled_ = true
                                    checked_ = true
                                }else{
                                    disabled_ = false
                                    checked_ = false
                                }
                            }else{
                                disabled_ = false
                                checked_ = false
                            }
                            let IPS = [];
                            if(item.addresses&&item.addresses.length!=0){
                                for(let i=0;i<item.addresses.length;i++){
                                    if(item.addresses[i].ips&&item.addresses[i].ips.length!=0){
                                        for (let index = 0; index < item.addresses[i].ips.length; index++) {
                                            const element = item.addresses[i].ips[index];
                                            IPS.push(element.ipAddress);
                                        }
                                    }
                                }
                            }
                            $this.dataVmList.push({
                                name:item.name,
                                id:item.id,
                                IP:IPS,
                                networkName:item.networkName,
                                _disabled: disabled_,
                                _checked:checked_,
                            })
                            if($this.selectedVmDataTable.indexOf(item.id) > -1){
                                $this.colFormV.selectedVmData.push({
                                    name:item.name,
                                    id:item.id,
                                    IP:IPS,
                                    _disabled: false,
                                    _checked:true,
                                })
                            }
                        })
                    }
                })
            },
            switchineVmCurrentPage(numberPage){
                this.vmCurrentPage = numberPage;
                this.getVmList()
            },
            switchVmItemPage(numberSize){
                this.vmItemPage = numberSize
                this.getVmList()
            },
            addSelectedData(){
                let that = this,bol = true;
                $.each(that.selectedDataConfiger,function(i,item){
                    if(that.selectedVmDataTable.indexOf(item.id)!=-1){
                        
                    }else{
                        bol = false
                        that.addVmAfterTable(item)
                        that.selectedVmDataTable.push(item.id)
                        that.colFormV.selectedVmData.push({
                            "name":item.name,
                            "id":item.id
                        })
                    }
                })
                if(bol){
                    that.$Message.info("请选择要添加的内容")
                }
            },
            addVmAfterTable(param){
                let data = this.dataVmList;
                $.each(this.dataVmList,function(i,item){
                    if(item.id==param.id){
                        item._checked = true;
                        item._disabled = true;
                    }
                })
            },
            refreshVmList(){
                this.getVmList()
            },
            filterNetVm(val){
                if(val){
                    this.networkId = val.value
                }else{
                    this.networkId = ''
                }
                this.getVmList()
            },
            // 提交采集任务
            colSubmitBtn(name){
                if(this.isCreat){
                    this.addColSub(name)
                }else{
                    this.modifySub(name)
                }
            },
            addColSub(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let form = {
                            "configId": this.colFormV.configId,
                            "configName": this.colFormV.configName,
                            "deviceIds": '',
                            "deviceType": 'VM',
                            // "matchMode": this.colFormV.matchMode,
                            // "matchProperty": this.colFormV.matchProperty,
                            // "matchRule": this.colFormV.matchRule,
                            "name": this.colFormV.name,
                            "taskType": this.colFormV.taskType,
                            "trainingId": this.sceneID
                        }
                        let ids = this.colFormV.selectedVmData.map((item)=>{
                            return item.id
                        }).join(',')
                        form.deviceIds = ids
                        if(form.deviceIds == ''){
                            this.$Message.error('请最少选择一台虚拟机')
                            return false
                        }
                        this.colLoading = true
                        addCollTask(form)
                        .then(res=>{
                            if(res.data.code === 1){
                                this.addColModel = false
                                this.getColData()
                                this.$Message.success({
                                    content:'添加成功',
                                    duration:3,
                                })
                            }else{
                                this.$Message.error({
                                    content:res.data.message,
                                    duration:5,
                                })
                            }
                            this.colLoading = false
                        })
                        .catch(err=>{
                            console.log(err)
                        })
                    }else{
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            resetBtn(name){
                this.$refs[name].resetFields();
            },
            // 删除采集任务
            delColTask(row){
                delColTask(row.id)
                .then(res=>{
                    console.log(res)
                    if(res.data.code === 1){
                        this.getColData()
                        this.$Message.success({
                            content:'删除成功',
                            duration:3
                        })
                    }else{
                        this.$Message.error({
                            content:res.data.message,
                            duration:5
                        })
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 修改采集任务
            modifyTask(row){
                this.modifyId = row.id
                this.isCreat = false
                let arr = row.deviceIds.split(',')
                this.selectedVmDataTable = arr
                this.loadConfiguration("qga_execute_cmd")
                this.getVmList()
                this.colFormV = {
                    configId:row.configId,
                    configName:row.configName,
                    taskType:row.taskType,
                    name:row.name,
                    selectedVmData:[],
                }
                this.addColModel = true
            },
            modifySub(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let form = {
                            "configId": this.colFormV.configId,
                            "configName": this.colFormV.configName,
                            "deviceIds": '',
                            "deviceType": 'VM',
                            "name": this.colFormV.name,
                            "taskType": this.colFormV.taskType,
                            "trainingId": this.sceneID,
                            id:this.modifyId,
                        }
                        let ids = this.colFormV.selectedVmData.map((item)=>{
                            return item.id
                        }).join(',')
                        form.deviceIds = ids
                        if(form.deviceIds == ''){
                            this.$Message.error('请最少选择一台虚拟机')
                            return false
                        }
                        this.colLoading = true
                        modifyColTask(form)
                        .then(res=>{
                            if(res.data.code === 1){
                                this.addColModel = false
                                this.getColData()
                                this.$Message.success({
                                    content:'添加成功',
                                    duration:3,
                                })
                            }else{
                                this.$Message.error({
                                    content:res.data.message,
                                    duration:5,
                                })
                            }
                            this.colLoading = false
                        })
                        .catch(err=>{
                            console.log(err)
                        })
                    }else{
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            // 获取子网络列表
            getSubnetList(){
                let params = {
                    id:this.projectId,
                    type:'NW',
                }
                subnetData(params)
                .then(res=>{
                    if(res.data.code === 1){
                       this.subnetList = res.data.data.networks || []
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
        }   
    }
</script>
<style scoped>
    .pageStyleVm{
        text-align: center
    }
    .starlet{
        color: red;
        position: absolute;
        left: -60px;
        font-size: 18px;
        line-height: 38px;
        font-weight: 800;
    }
</style>

